const Service = require('egg').Service;
const svgCaptcha = require('svg-captcha');
const nodemailer = require('nodemailer');

interface captchaOpton {
  size?: Number,
  fontSize?: Number,
  width?: Number,
  height?: Number,
  bacground?: Number,
}

interface emailOption {
  revicer: String,
  title: String,
  text?: String,
  content: String,
}

// 封装发送者信息
const transporter = nodemailer.createTransport({
  host: 'smtp.163.com', // 调用qq服务器
  secureConnection: true, // 启动SSL
  port: 465, // 端口就是465
  auth: {
    user: 'itfreevip@163.com', // 账号
    pass: 'MLKMQTAZJIRFNCET', // 授权码,
    // MLKMQTAZJIRFNCET 授权码
  },
});

class ToolsService extends Service {
  // 产生验证码
  async captcha(option: captchaOpton = {}) {
    let AssignObj = Object.assign({
      size: 4,
      fontSize: 50,
      width: 100,
      noise: 3,// 干扰线数
      height: 40,
      bacground: '#fff'
    }, option);
    const captcha = svgCaptcha.create(AssignObj);
    return captcha;
  }

  async email(option: emailOption) {
    let info = await transporter.sendMail({
      from: '"IT优资社区"<itfreevip@163.com>', // sender address
      to: option.revicer, // list of receivers
      subject: option.title ? option.title : '', // Subject line
      text: option.text, // plain text body
      html: option.content // html body
    });
    console.log('Message sent: %s', info.messageId);
    // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

    // Preview only available when sending through an Ethereal account
    console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
    // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
    return true;
  }
}

export default ToolsService;
